import pymysql
from pymysql.cursors import DictCursor

CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'db': 'duanhh',
    'charset': 'utf8'
}


class DB():
    def __init__(self):
        self.conn = pymysql.connect(**CONFIG)

    def __enter__(self):
        return self.conn.cursor()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.conn.rollback()
        else:
            self.conn.commit()

    def close(self):
        if self.conn:
            self.conn.close()
            self.conn = None


class baseDao():
    def __init__(self):
        self.db = DB()

    def find_all(self, table, where=None, *args):
        sql = '''
        select * from %s
        ''' % table
        print(sql)
        if where:
            sql += where
        with self.db as c:
            c.execute(sql, args)
            result = c.fetchall()
        return result